Spring笔记(四)—— IOC 容器之 Bean 的生命周期

Initialization 回调

org.springframework.beans.factory.InitializingBean 接口允许 bean 在容器设置完所有属性后执行初始化工作,初始化工作在实现 InitializingBean 的类中的 afterPropertiesSet() 方法中执行。此外,初始化工作也可通过 @PostConstruct 注解来指定执行初始化工作的方法;或者指定一个 POJO 的初始化方法,然后在 XML 文件中使用 init-method 属性指定在该方法中执行初始化操作。

实现 InitializingBean 接口

1
<bean id="exampleInitBean" class="examples.ExampleBean"/>
1
2
3
4
5
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}

使用 @PostConstruct 注解

1
2
3
4
5
6
public class CachingMovieLister {
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
}

使用 init-method 属性

1
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
1
2
3
4
5
public class ExampleBean {
public void init() {
// do some initialization work
}
}

Destroy 回调

org.springframework.beans.factory.DisposableBean 接口允许 bean 使用销毁回调,销毁工作在实现 DisposableBean 的类中的 destroy() 方法中执行。注解方法使用 @PreDestroy,XML 文件指定 destroy-method 属性即可。

实现 InitializingBean 接口

1
<bean id="exampleInitBean" class="examples.ExampleBean"/>
1
2
3
4
5
public class ExampleBean implements InitializingBean {
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}

使用 @PostConstruct 注解

1
2
3
4
5
6
public class CachingMovieLister {
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}

使用 init-method 属性

1
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
1
2
3
4
5
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}

默认的 initialization 和 destroy 方法

当做 initialization 和 destroy 工作时,使用 init(), initialize(), dispose() 等类似的方法名有助于我们识别方法的作用。每次我们都需要为每个 bean 设置 init-method 或 destroy-method 属性指定生命周期的回调方法,有一个更加简便的方法,即在 元素中使用 default-init-method 属性指定初始化的方法,则默认 元素下的所有 bean 的初始化方法均为 init()。

1
2
3
4
5
<beans default-init-method="init">
<bean id="blogService" class="com.foo.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>

1
2
3
4
5
6
7
8
9
10
11
12
public class DefaultBlogService implements BlogService {
private BlogDao blogDao;
public void setBlogDao(BlogDao blogDao) {
this.blogDao = blogDao;
}
// this is (unsurprisingly) the initialization callback method
public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
}

default-destroy-method 属性的使用方法也和 default-init-method 一样。

参考资料:

Spring 3.x 企业应用开发实战
Spring Framework Reference Documentation

热评文章